let mongoose = require('mongoose');

module.exports = {
    async add(options){
        let FriendlyLinkGroupModel = mongoose.models['FriendlyLinkGroup'];
        let data = await FriendlyLinkGroupModel.findOne({scene: options.scene});
        if((!options.version) && data){
            throw new Error("该链接组已存在");
        }
        delete options._id;
        if(options.version && options.version != ''){
            options.timeTick = new Date().getTime();
        }
        await FriendlyLinkGroupModel.create(options);
    },
    async delete(options){
        let FriendlyLinkGroupModel = mongoose.models['FriendlyLinkGroup'];
        let obj = options.version == undefined ? {_id: options._id.toString()} : {version: options.version};
        await FriendlyLinkGroupModel.remove(obj);
    },
    async edit(options){
        let FriendlyLinkGroupModel = mongoose.models['FriendlyLinkGroup'];
        let data = await FriendlyLinkGroupModel.findOne({_id: options._id.toString()});
        if(!data){
            throw new Error("修改的链接组不存在");
        }
        let data2 = await FriendlyLinkGroupModel.findOne({_id: {$ne: data._id.toString()}, scene: options.scene});
        if(!options.version && data2){
            throw new Error("修改的场景名已存在");
        }
        delete options._id;
        await FriendlyLinkGroupModel.update({_id: data._id.toString()}, options);
    },
    async find(options){
        let FriendlyLinkModel = mongoose.models['FriendlyLink'];
        let FriendlyLinkGroupModel = mongoose.models['FriendlyLinkGroup'];
        let version = options.version == "" ? null : options.version;
        let data = await FriendlyLinkGroupModel.find({version});
        for(let item of data){
            item = item._doc;
            let listArr = item.list.split(',');
            item.list = [];
            for(let key in listArr){
                let data = await FriendlyLinkModel.findOne({name: listArr[key]});
                if(data){
                    item.list.push(data);
                }
            }
        }
        // console.log('data =', data);
        return data;
    },
    async findVersions(options){
        let FriendlyLinkGroupModel = mongoose.models['FriendlyLinkGroup'];
        let data = await FriendlyLinkGroupModel.aggregate([ {$group: {_id: '$version'}} ]);
        data.sort((a, b) => {
            let index1 = a._id ? a._id.split('.').join('') : 0;
            let index2 = b._id ? b._id.split('.').join('') : 0;
            return index1 - index2;
        });
        // console.log('data ==', data);
        let versions = '';
        for(let item of data){
            versions += versions === '' ? item._id : ('-' + item._id);
        }
        console.log('versions =', versions);
        return versions;
    }
};
